﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Codeplex.Data;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Globalization;
using System.Runtime.Serialization.Formatters.Binary;

namespace nanobot {

    public class Buyorder {
        public double price { get; set; }
        public double quantity { get; set; }
        public double total { get; set; }
    }

    public class RecentTrade {
        private int id_n;
        public int id {
            get {
                return id_n;
            }
            set {
                //if ( value.HasValue )
                //    i = value.Value;
                //else
                //    i = null;
                try {
                    id_n = value;

                } catch ( Exception ) {
                    id_n = 0;
                    throw;
                }
            }
        }

        private DateTime ti;
        public DateTime time {
            get {
                return ti;
            }
            set {
                if ( value == null ) ti = new DateTime(); else ti = value;
            }
        }
        public string type { get; set; }
        public double price { get; set; }
        public double quantity { get; set; }
        public double total { get; set; }

    }

    public class SellOrder {
        public double price { get; set; }
        public double quantity { get; set; }
        public double total { get; set; }

    }

    public class Market {

        public Market () {

        }

        public Market ( Buyorder[] buyorders, string label, double lasttradeprice
            , DateTime lasttradetime, int marketid, string primarycode
            , string primaryname, RecentTrade[] recenttrade, string secondarycode
            , string secondaryname, SellOrder[] sellorders, double volume ) {

            this.buyorders = new Buyorder[buyorders.Length];
            Buyorder b;
            for ( int i = 0; i < this.buyorders.Length; i++ ) {
                b = new Buyorder();
                b.price = buyorders[i].price;
                b.quantity = buyorders[i].quantity;
                b.total = buyorders[i].total;
                this.buyorders[i] = b;
            }
            this.label = label;
            this.lasttradeprice = lasttradeprice;
            this.lasttradetime = lasttradetime;
            this.marketid = marketid;
            this.primarycode = primarycode;
            this.primaryname = primaryname;
            this.recenttrades = new RecentTrade[recenttrades.Length];
            RecentTrade r;
            for ( int i = 0; i < this.recenttrades.Length; i++ ) {
                r = new RecentTrade();
                r.id = recenttrades[i].id;
                r.price = recenttrades[i].price;
                r.quantity = recenttrades[i].quantity;
                r.time = recenttrades[i].time;
                r.total = recenttrades[i].total;
                r.type = recenttrades[i].type;
                this.recenttrades[i] = r;
            }
            this.secondarycode = secondarycode;
            this.secondaryname = secondaryname;
            this.sellorders = new SellOrder[sellorders.Length];
            SellOrder s;
            for ( int i = 0; i < this.sellorders.Length; i++ ) {
                s = new SellOrder();
                s.price = sellorders[i].price;
                s.quantity = sellorders[i].quantity;
                s.total = sellorders[i].total;
                this.sellorders[i] = s;
            }
            this.volume = volume;

        }

        public Buyorder[] buyorders { get; set; }
        public string label { get; set; }
        private double lasttradeprice_n;
        public double lasttradeprice {
            get {
                return lasttradeprice_n;
            }
            set {
                try {
                    lasttradeprice_n = value;
                } catch {
                    lasttradeprice_n = 0d;
                    throw;
                }
            }
        }

        private DateTime lasttradetime_n;
        public DateTime lasttradetime { get; set; }
        public int marketid { get; set; }
        public string primarycode { get; set; }
        public string primaryname { get; set; }
        public RecentTrade[] recenttrades { get; set; }
        public string secondarycode { get; set; }
        public string secondaryname { get; set; }
        public SellOrder[] sellorders { get; set; }
        public double volume { get; set; }

    }

    public static class CRYPTSYcom {
        public static string API_Public_Key { get; set; }
        public static string API_Private_Key { get; set; }
        private static string api_key_registry_key = "cryptsy_API_KEY";
        public static string API_KEY_registry_key { get { return api_key_registry_key; } }
        private static string api_private_key_registry_key = "cryptsy_API_Private_KEY";
        public static string API_Private_KEY_registry_key { get { return api_private_key_registry_key; } }
        private static string private_api_url = "https://api.cryptsy.com/api";
        public static string Private_API_URL { get { return private_api_url; } }


        public static string cryptsy_pairs_file_name = "Cryptsy_pairs";

        public static volatile bool download_all_market_data_complete;
        public static volatile bool download_all_market_data_running;
        public static volatile bool download_single_market_data_complete;

        public static List<string[]> DownloadedData1 { get; set; }
        public static List<string[]> DownloadedData2 { get; set; }
        public static string Error { get; set; }
        public static string Success { get; set; }
        public static object Data1 { get; set; }
        public static object Data2 { get; set; }

        public static bool first_run;
        //private static string [] pairs;
        private static Dictionary<string, Market> market_all;
        private static Dictionary<int, string> market_id_pair;
        private static Dictionary<string, int> market_pair_id;

        static CRYPTSYcom () {
            download_all_market_data_complete = false;
            download_all_market_data_running = false;
            download_single_market_data_complete = false;
            Data1 = null;

            API_Public_Key = ModifyRegistry.Read( API_KEY_registry_key );
            API_Private_Key = ModifyRegistry.Read( API_Private_KEY_registry_key );

            if ( File.Exists( cryptsy_pairs_file_name ) ) {
                first_run = false;

            } else {
                first_run = true;

            }


        }

        private static void Query_Async ( string method, Dictionary<string, object> parameters = null ) {
            string cmd_line_argv = "method=" + method + "&public=" + CRYPTSYcom.API_Public_Key
                                + "&private=" + CRYPTSYcom.API_Private_Key;

            if ( parameters != null ) {
                foreach ( var item in parameters ) {
                    cmd_line_argv += "&" + item.Key + "=" + item.Value;

                }
            }


            try {
                using ( var client = new WebClient() ) {
                    client.DownloadStringCompleted += client_DownloadStringCompleted;
                    client.DownloadStringAsync(
                        new Uri( "http://localhost//nanobot//cryptsy.com.php?" + cmd_line_argv ),
                        method
                    );

                }
            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }




        }

        private static void client_DownloadStringCompleted ( object sender, DownloadStringCompletedEventArgs e ) {
            string method = ( string ) e.UserState;
            string result = ( string ) e.Result;

            switch ( method ) {
                case "getinfo":
                    _GetAccountInfo( result );

                    break;

                case "getmarkets":
                    _GetMarkets( result );

                    break;

                case "getcoindata":
                    _GetCoinData( result );

                    break;

                case "mytransactions":
                    _GetMyTransaction( result );

                    break;

                case "markettrades":
                    _GetMarketTrades( result );

                    break;

                case "marketorders":
                    _GetMarketOrders( result );

                    break;

                case "mytrades":
                    _GetMyTrades( result );

                    break;

                case "allmytrades":
                    _GetAllMyTrades( result );

                    break;

                case "myorders":
                    _GetMyOrders( result );

                    break;

                case "depth":
                    _GetDepth( result );
                    break;

                case "allmyorders":
                    _GetAllMyOrders( result );

                    break;

                case "createorder":
                    _CreateOrder( result );

                    break;

                case "cancelmarketorders":
                    _CancelMarketOrders( result );

                    break;

                case "cancelallorders":
                    _CancelAllOrders( result );

                    break;

                case "calculatefees":
                    _CalulateFees( result );

                    break;

                case "generatenewaddress":
                    _GenerateNewAddress( result );

                    break;

                case "mytransfers":
                    _MyTransfers( result );

                    break;

                case "makewithdrawal":
                    _MakeWithdrawal( result );

                    break;

                case "getmydepositaddresses":
                    _GetmyDepositAddresses( result );

                    break;

                case "getorderstatus":
                    _getorderstatus( result );

                    break;

                default:
                    break;
            }




        }

        /// <summary>
        /// not finished
        /// </summary>
        public static void GetRecentTrades () {


        }
        private static void _GetRecentTrades ( string result ) {

        }

        /// <summary>
        /// not finished
        /// </summary>
        public static void GetBuyOrders () {

        }
        private static void _GetBuyOrders ( string result ) {

        }

        /// <summary>
        /// not finished
        /// </summary>
        public static void GetSellOrders () {

        }
        private static void _GetSellOrders ( string result ) {

        }

        public static void GetMarkets () {
            Query_Async( "getmarkets" );


        }
        private static void _GetMarkets ( string result ) {
            DownloadedData1.Clear();

            dynamic json;
            dynamic [] json2;
            dynamic [] temp;

            try {
                result = result.Replace( "return", "returned" );
                result = result.Replace( @"\/", "-" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {

                    json2 = ( dynamic[] ) json.returned;

                    foreach ( var item in json2 ) {
                        temp = ( dynamic[] ) item;
                        DownloadedData1.Add(
                            new string[] { 
                            temp[0].Value,
                            temp[1].Value,
                            temp[2].Value,
                            temp[3].Value,
                            temp[4].Value,
                            temp[5].Value,
                            temp[6].Value,
                            temp[7].Value,
                            temp[8].Value,
                            temp[9].Value,
                            temp[10].Value,
                            temp[11].Value,
                            temp[12].Value
                        }
                        );
                    }
                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }
        }

        public static void GetAccountInfo () {
            Query_Async( "getinfo" );

        }
        private static void _GetAccountInfo ( string result ) {
            DownloadedData1.Clear();
            DownloadedData2.Clear();

            dynamic json;
            dynamic [] json2;
            dynamic [] temp;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {

                    json2 = ( dynamic[] ) json.returned;

                    temp = ( dynamic[] ) json2[0].Value;


                    foreach ( var item in temp ) {
                        if ( item.Key == "item" ) {
                            DownloadedData1.Add(
                                new string[]{
                                "42",
                                item.Value
                            }
                            );

                        } else {
                            DownloadedData1.Add(
                                new string[]{
                                item.Key,
                                item.Value
                            }
                            );

                        }

                    }


                    temp = ( dynamic[] ) json2[1].Value;
                    foreach ( var item in temp ) {
                        if ( item.Key == "item" ) {
                            DownloadedData2.Add(
                                new string[]{
                                "42",
                                item.Value
                            }
                            );

                        } else {
                            DownloadedData2.Add(
                                new string[]{
                                item.Key,
                                item.Value
                            }
                            );

                        }

                    }

                    Data1 = ( int ) json2[5].Value;
                }



            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }

        }

        public static void GetCoinData () {
            Query_Async( "getcoindata" );

        }
        private static void _GetCoinData ( string result ) {
            DownloadedData1.Clear();

            dynamic json;
            dynamic [] json2;
            dynamic [] temp;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {

                    json2 = ( dynamic[] ) json.returned;

                    temp = ( dynamic[] ) json2[0].Value;


                    foreach ( var item in temp ) {
                        DownloadedData1.Add(
                            new string[]{
                            item.code,
                            item.currencyid,
                            item.maintenancemode,
                            item.name,
                            item.withdrawalfee
                        }
                        );


                    }
                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }
        }

        /// <summary>
        /// not finished
        /// </summary>
        public static void GetMyTransaction () {
            Query_Async( "mytransactions" );

        }
        private static void _GetMyTransaction ( string result ) {
            DownloadedData1.Clear();

            dynamic json;
            dynamic [] json2;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {

                    json2 = ( dynamic[] ) json.returned;

                    foreach ( var item in json2 ) {
                        DownloadedData1.Add(
                            new string[]{

                        }
                        );


                    }
                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }
        }

        /// <summary>
        /// not finished
        /// </summary>
        /// <param name="marketid"></param>
        public static void GetMarketTrades ( int marketid ) {
            Dictionary<string, object> parameter = new Dictionary<string, object>();
            parameter["marketid"] = marketid;
            Query_Async( "markettrades", parameter );

        }
        private static void _GetMarketTrades ( string result ) {
            DownloadedData1.Clear();

            dynamic json;
            dynamic [] json2;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {
                    json2 = ( dynamic[] ) json.returned;

                    foreach ( var item in json2 ) {
                        DownloadedData1.Add(
                            new string[]{
                                item.datetime,
                                item.initiate_ordertype,
                                item.quantity,
                                item.total,
                                item.tradeid,
                                item.tradeprice
                            }
                        );


                    }
                } else {
                    Error = json.error;

                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }
        }

        public static void GetMarketOrders ( int marketid ) {
            Dictionary<string, object> parameter = new Dictionary<string, object>();
            parameter["marketid"] = marketid;
            Query_Async( "marketorders", parameter );

        }
        private static void _GetMarketOrders ( string result ) {
            DownloadedData1.Clear();
            DownloadedData2.Clear();

            dynamic json;
            dynamic [] json2;
            dynamic [] temp;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {

                    json2 = ( dynamic[] ) json.returned;

                    temp = ( dynamic[] ) json[0].Value;
                    foreach ( var item in temp ) {
                        DownloadedData1.Add(
                            new string[]{
                                item.quantity,
                                item.sellprice,
                                item.total
                            }
                        );


                    }


                    temp = ( dynamic[] ) json[1].Value;
                    foreach ( var item in temp ) {
                        DownloadedData2.Add(
                            new string[]{
                                item.quantity,
                                item.buyprice,
                                item.total
                            }
                        );


                    }
                } else {
                    Error = json.error;

                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }

        }

        /// <summary>
        /// not finished
        /// </summary>
        /// <param name="marketid"></param>
        /// <param name="limit"></param>
        public static void GetMyTrades ( int marketid, int limit ) {
            Dictionary<string, object> parameter = new Dictionary<string, object>();
            parameter["marketid"] = marketid;
            parameter["limit"] = limit;
            Query_Async( "mytrades", parameter );

        }
        private static void _GetMyTrades ( string result ) {
            DownloadedData1.Clear();

            dynamic json;
            dynamic [] json2;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {
                    json2 = ( dynamic[] ) json.returned;

                    foreach ( var item in json2 ) {
                        DownloadedData1.Add(
                            new string[]{


                            }
                        );


                    }
                } else {
                    Error = json.error;

                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }

        }

        /// <summary>
        /// not finished
        /// </summary>
        /// <param name="startdate"></param>
        /// <param name="enddate"></param>
        public static void GetAllMyTrades ( DateTime startdate, DateTime enddate ) {
            Dictionary<string, object> parameter = new Dictionary<string, object>();
            parameter["startdate"] = startdate.ToString( "yyyy-MM-dd" );
            parameter["enddate"] = enddate.ToString( "yyyy-MM-dd" );
            Query_Async( "allmytrades", parameter );

        }
        private static void _GetAllMyTrades ( string result ) {
            DownloadedData1.Clear();

            dynamic json;
            dynamic [] json2;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {
                    json2 = ( dynamic[] ) json.returned;

                    foreach ( var item in json2 ) {
                        DownloadedData1.Add(
                            new string[]{


                            }
                        );


                    }
                } else {
                    Error = json.error;

                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }

        }

        /// <summary>
        /// not finished
        /// </summary>
        /// <param name="marketid"></param>
        public static void GetMyOrders ( int marketid ) {
            Dictionary<string, object> parameter = new Dictionary<string, object>();
            parameter["marketid"] = marketid;
            Query_Async( "myorders", parameter );

        }
        private static void _GetMyOrders ( string result ) {
            DownloadedData1.Clear();

            dynamic json;
            dynamic [] json2;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {
                    json2 = ( dynamic[] ) json.returned;

                    foreach ( var item in json2 ) {
                        DownloadedData1.Add(
                            new string[]{


                            }
                        );


                    }
                } else {
                    Error = json.error;

                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }

        }

        public static void GetDepth ( int marketid ) {
            Dictionary<string, object> parameter = new Dictionary<string, object>();
            parameter["marketid"] = marketid;
            Query_Async( "depth", parameter );

        }
        private static void _GetDepth ( string result ) {
            DownloadedData1.Clear();
            DownloadedData2.Clear();

            dynamic json;
            dynamic [] json2;
            dynamic [] temp;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {

                    json2 = ( dynamic[] ) json.returned;

                    temp = ( dynamic[] ) json[0].Value;
                    foreach ( var item in temp ) {
                        DownloadedData1.Add(
                            new string[]{
                                item[0],
                                item[1]
                            }
                        );


                    }


                    temp = ( dynamic[] ) json[1].Value;
                    foreach ( var item in temp ) {
                        DownloadedData2.Add(
                            new string[]{
                                item[0],
                                item[1]
                            }
                        );


                    }
                } else {
                    Error = json.error;

                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }

        }

        /// <summary>
        /// not finished
        /// </summary>
        public static void GetAllMyOrders () {
            Query_Async( "allmyorders" );

        }
        private static void _GetAllMyOrders ( string result ) {
            DownloadedData1.Clear();

            dynamic json;
            dynamic [] json2;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {
                    json2 = ( dynamic[] ) json.returned;

                    foreach ( var item in json2 ) {
                        DownloadedData1.Add(
                            new string[]{


                            }
                        );


                    }
                } else {
                    Error = json.error;

                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }

        }

        /// <summary>
        /// not finished
        /// note: "{\"success\":\"0\",\"error\":\"Insufficient 42 in account to complete this order.\"}"
        /// </summary>
        /// <param name="marketid"></param>
        /// <param name="ordertype"></param>
        /// <param name="quantity"></param>
        /// <param name="price"></param>
        public static void CreateOrder ( int marketid, int ordertype, double quantity, double price ) {
            Dictionary<string, object> parameter = new Dictionary<string, object>();
            parameter["marketid"] = marketid;
            parameter["ordertype"] = ordertype;
            parameter["quantity"] = quantity;
            parameter["price"] = price;

            Query_Async( "createorder", parameter );

        }
        private static void _CreateOrder ( string result ) {
            dynamic json;
            Data1 = null;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );

                Success = json.success;

                if ( Success == "1" ) {
                    Data1 = int.Parse( ( string ) json.returned.orderid );

                } else {
                    Error = json.error;

                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }

        }

        /// <summary>
        /// not finished
        /// note: "{\"success\":\"0\",\"error\":\"Order not found.\"}"
        /// </summary>
        /// <param name="orderid"></param>
        public static void CancelOrder ( int orderid ) {
            Dictionary<string, object> parameter = new Dictionary<string, object>();
            parameter["orderid"] = orderid;
            Query_Async( "orderid", parameter );

        }
        private static void _CancelOrder ( string result ) {
            dynamic json;
            Data1 = null;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {
                    Data1 = int.Parse( ( string ) json.returned );

                } else {
                    Error = json.error;
                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }

        }

        /// <summary>
        /// not finished
        /// </summary>
        /// <param name="marketid"></param>
        public static void CancelMarketOrders ( int marketid ) {
            Dictionary<string, object> parameter = new Dictionary<string, object>();
            parameter["marketid"] = marketid;
            Query_Async( "cancelmarketorders", parameter );

        }
        private static void _CancelMarketOrders ( string result ) {
            dynamic json;
            Data1 = null;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {
                    //json2 = ( dynamic[] ) json2.returned;
                    //Data1 = int.Parse( ( string ) json.returned );

                } else {
                    Error = json.error;

                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }

        }

        /// <summary>
        /// not finished
        /// </summary>
        public static void CancelAllOrders () {
            Query_Async( "cancelallorders" );

        }
        private static void _CancelAllOrders ( string result ) {
            dynamic json;
            Data1 = null;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {
                    //json2 = ( dynamic[] ) json2.returned;
                    //Data1 = int.Parse( ( string ) json.returned );

                } else {
                    Error = json.error;

                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }

        }


        public static void CalculateFees ( int ordertype, double quantity, double price ) {
            Dictionary<string, object> parameter = new Dictionary<string, object>();
            parameter["ordertype"] = ordertype;
            parameter["quantity"] = quantity;
            parameter["price"] = price;
            Query_Async( "calculatefees", parameter );
        }
        private static void _CalulateFees ( string result ) {
            dynamic json;
            dynamic [] json2;
            Data1 = null;
            Data2 = null;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {
                    json2 = ( dynamic[] ) json.returned;
                    Data1 = double.Parse( ( string ) json2[0].Value, new CultureInfo( "en-us" ) );
                    Data2 = double.Parse( ( string ) json2[1].Value, new CultureInfo( "en-us" ) );
                } else {
                    Error = json.error;

                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }

        }

        public static void GenerateNewAddress ( int currencyid ) {
            Dictionary<string, object> parameter = new Dictionary<string, object>();
            parameter["currencyid"] = currencyid;
            Query_Async( "generatenewaddress", parameter );

        }
        public static void GenerateNewAddress ( string currencycode ) {
            Dictionary<string, object> parameter = new Dictionary<string, object>();
            parameter["currencycode"] = currencycode;
            Query_Async( "generatenewaddress", parameter );

        }
        private static void _GenerateNewAddress ( string result ) {
            dynamic json;
            Data1 = null;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {
                    Data1 = json.returned.address;

                } else {
                    Error = json.error;

                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }

        }

        /// <summary>
        /// not finished
        /// </summary>
        public static void MyTransfers () {
            Query_Async( "mytransfers" );

        }
        private static void _MyTransfers ( string result ) {
            DownloadedData1.Clear();

            dynamic json;
            dynamic [] json2;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {
                    json2 = ( dynamic[] ) json.returned;

                    foreach ( var item in json2 ) {
                        DownloadedData1.Add(
                            new string[]{


                            }
                        );


                    }
                } else {
                    Error = json.error;

                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }

        }

        /// <summary>
        /// note: "{\"success\":\"0\",\"error\":\"Error: a\\u00f6klshdoiashdahd is not a trusted address on your account\"}"
        /// </summary>
        /// <param name="address"></param>
        /// <param name="amount"></param>
        public static void MakeWithdrawal ( string address, double amount ) {
            Dictionary<string, object> parameter = new Dictionary<string, object>();
            parameter["address"] = address;
            parameter["amount"] = amount;
            Query_Async( "makewithdrawal", parameter );

        }
        private static void _MakeWithdrawal ( string result ) {
            dynamic json;
            Data1 = null;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;
                if ( Success != "1" ) {
                    Data1 = json.error;

                } else {
                    Error = json.error;

                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }
        }

        public static void GetmyDepositAddresses () {
            Query_Async( "getmydepositaddresses" );

        }
        private static void _GetmyDepositAddresses ( string result ) {
            DownloadedData1.Clear();

            dynamic json;
            dynamic [] json2;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {
                    json2 = ( dynamic[] ) json.returned;

                    foreach ( var item in json2 ) {
                        DownloadedData1.Add(
                            new string[]{
                                item.Key,
                                item.Value

                            }
                        );


                    }
                } else {
                    Error = json.error;

                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }
        }

        /// <summary>
        /// not finished
        /// note: "{\"success\":\"1\",\"return\":{\"orderinfo\":{\"active\":0,\"remainqty\":0},\"tradeinfo\":[]}}"
        /// </summary>
        /// <param name="orderid"></param>
        public static void getorderstatus ( int orderid ) {
            Dictionary<string, object> parameter = new Dictionary<string, object>();
            parameter["orderid"] = orderid;
            Query_Async( "getorderstatus", parameter );

        }
        private static void _getorderstatus ( string result ) {
            DownloadedData1.Clear();
            Data1 = null;
            Data2 = null;

            dynamic json;
            dynamic [] json2;

            try {
                result = result.Replace( "return", "returned" );
                json = ( dynamic ) DynamicJson.Parse( result );
                Success = json.success;

                if ( Success == "1" ) {
                    json2 = ( dynamic[] ) json.returned;
                    dynamic[] json3 = ( dynamic[] ) json2[0].Value;
                    dynamic[] json4 = ( dynamic[] ) json2[1].Value;

                    Data1 = json3[0].Value;
                    Data2 = json3[1].Value;

                    foreach ( var item in json4 ) {
                        DownloadedData1.Add(
                            new string[]{


                            }
                        );


                    }
                } else {
                    Error = json.error;

                }

            } catch ( Exception ex ) {
                MessageBox.Show( ex.Message, "Error" );

            }

        }


        //-----
        public static void firstRun () {

        }

        public static void initialization_not_first_run () {
            //using ( StreamReader sr = new StreamReader( cryptsy_pairs_file_name ) ) {
            //    string content = sr.ReadToEnd();
            //    string [] pair_id = content.Split( new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries );
            //    string [] temp;
            //    market_pair_id = new Dictionary<int, string>();
            //    market_all = new Dictionary<string, Market>();
            //    for ( int i = 4; i < pair_id.Length; i++ ) {
            //        temp = pair_id[i].Split( new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries );
            //        market_pair_id.Add( HelperClass.Parse_int( temp[0] ), temp[1] );
            //    }
            //
            //}
        }

        private static Market jsonToMarket ( dynamic json ) {
            Market mar = new Market();
            mar.marketid = json.marketid == null ? -1 : HelperClass.Parse_int( json.marketid );
            mar.label = json.label == null ? "null" : ( string ) json.label;
            mar.lasttradeprice = json.lasttradeprice == null ? -1 : HelperClass.Parse_double( ( string ) json.lasttradeprice );
            mar.volume = json.volume == null ? -1 : HelperClass.Parse_double( json.volume );
            mar.lasttradetime = json.lasttradetime == null ? DateTime.MinValue : HelperClass.getDateTimeFromJsonString( json.lasttradetime );
            mar.primaryname = json.primaryname == null ? "null" : ( string ) json.primaryname;
            mar.primarycode = json.primarycode == null ? "null" : ( string ) json.primarycode;
            mar.secondaryname = json.secondaryname == null ? "null" : ( string ) json.secondaryname;
            mar.secondarycode = json.secondarycode == null ? "null" : ( string ) json.secondarycode;

            List<RecentTrade> recenttrade_list = new List<RecentTrade>();
            RecentTrade recenttrade;
            if ( json.recenttrades != null ) {
                foreach ( var c in json.recenttrades ) {
                    recenttrade = new RecentTrade();
                    recenttrade.id = c.id == null ? -1 : HelperClass.Parse_int( c.id );
                    recenttrade.price = c.price == null ? -1 : HelperClass.Parse_double( c.price );
                    recenttrade.quantity = c.quantity == null ? -1 : HelperClass.Parse_double( c.quantity );
                    recenttrade.time = c.time == null ? DateTime.MinValue : HelperClass.getDateTimeFromJsonString( c.time );
                    recenttrade.total = c.total == null ? -1 : HelperClass.Parse_double( c.total );
                    recenttrade.type = c.type == null ? "null" : c.type;
                    recenttrade_list.Add( recenttrade );
                }
                mar.recenttrades = recenttrade_list.ToArray();
            } else {
                mar.recenttrades = null;
            }

            List<SellOrder> sellorder_list = new List<SellOrder>();
            SellOrder sellorder;
            if ( json.sellorders != null ) {
                foreach ( var c in json.sellorders ) {
                    sellorder = new SellOrder();
                    sellorder.price = c.price == null ? -1 : HelperClass.Parse_double( c.price );
                    sellorder.quantity = c.quantity == null ? -1 : HelperClass.Parse_double( c.quantity );
                    sellorder.total = c.total == null ? -1 : HelperClass.Parse_double( c.total );
                    sellorder_list.Add( sellorder );
                }
                mar.sellorders = sellorder_list.ToArray();
            } else {
                mar.sellorders = null;
            }

            List<Buyorder> buyorder_list = new List<Buyorder>();
            Buyorder buyorder;
            if ( json.buyorders != null ) {
                foreach ( var c in json.buyorders ) {
                    buyorder = new Buyorder();
                    buyorder.price = c.price == null ? -1 : HelperClass.Parse_double( c.price );
                    buyorder.quantity = c.quantity == null ? -1 : HelperClass.Parse_double( c.quantity );
                    buyorder.total = c.total == null ? -1 : HelperClass.Parse_double( c.total );
                    buyorder_list.Add( buyorder );

                }
                mar.buyorders = buyorder_list.ToArray();
            } else {
                mar.buyorders = null;
            }

            return mar;

        }


    }
}